package com.example.jpatest.service.impl;

import com.example.jpatest.entity.Competition;
import com.example.jpatest.entity.Enter;
import com.example.jpatest.entity.Team;
import com.example.jpatest.repository.CompetitionRepository;
import com.example.jpatest.repository.EnterRepository;
import com.example.jpatest.service.CompetitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.Set;

import java.util.List;

/**
 * @author czx
 */
@Service
public class CompetitionServiceImpl implements CompetitionService {
    @Autowired
    CompetitionRepository competitionRepository;

    @Autowired
    EnterRepository enterRepository;

    @Override
    public Competition getCompetitionByName(String name) {
        return competitionRepository.findByName(name).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Competition saveCompetition(Competition competition) {
        return competitionRepository.save(competition);
    }

    @Override
    public List<Competition> getCompetitions() {
        return competitionRepository.findAll();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteCompetition(Competition competition) {
        for (Enter enter : competition.getEnters()) {
            competition.getEnters().remove(enter);
            enterRepository.delete(enter);
        }
        competitionRepository.delete(competition);
    }

    @Override
    public List<Team> getTeams(Competition competition) {
        List<Team> teams = new LinkedList<Team>();
        for (Enter enter : competition.getEnters()) {
            teams.add(enter.getTeam());
        }
        return teams;
    }
}
